import datetime as dt
import pytz
from scheduler.config import beat_dburi
import sqlalchemy as sa
from sqlalchemy import func
from sqlalchemy.event import listen
from sqlalchemy.orm import relationship, foreign, remote
from sqlalchemy.sql import select, insert, update
from celery_sqlalchemy_scheduler.session import session_cleanup, SessionManager, ModelBase
from celery_sqlalchemy_scheduler.models import ModelMixin

import logging

logger = logging.getLogger(__file__)


class CeleryBeatTaskLog(ModelBase, ModelMixin):
    __tablename__ = 'celery_beat_task_log'
    __table_args__ = {'sqlite_autoincrement': True}

    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
    task_id = sa.Column(sa.String(255), unique=True)
    # task name
    task = sa.Column(sa.String(255))
    # name
    name = sa.Column(sa.String(255))

    args = sa.Column(sa.Text(), default='[]')
    kwargs = sa.Column(sa.Text(), default='{}')

    # 修改时间
    date_changed = sa.Column(sa.DateTime(timezone=True),
                             default=func.now(), onupdate=func.now())
    result = sa.Column(sa.Boolean(), default=True)
    message = sa.Column(sa.Text(), default='')

    session = SessionManager().session_factory(dburi=beat_dburi)

    @classmethod
    def add(cls, **kwargs):
        session = cls.session
        with session_cleanup(session):
            task_log = None
            if 'task_id' in kwargs:
                task_log = session.query(TaskLog).filter_by(task_id=kwargs.get('task_id')).first()
            if not task_log:
                task_log = TaskLog.create(**kwargs)
            try:
                session.add(task_log)
                session.commit()
            except sa.exc.IntegrityError as exc:
                logger.error(exc)
                session.rollback()
                raise exc
            except Exception as exc:
                logger.error(exc)
                session.rollback()
                raise exc
            return task_log

class CeleryBeatTaskInfo(ModelBase, ModelMixin):
    __tablename__ = 'celery_beat_task_info'
    __table_args__ = {'sqlite_autoincrement': True}

    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
    name = sa.Column(sa.String(255), unique=True)
    task_name = sa.Column(sa.String(255))
    file_name = sa.Column(sa.String(255))
    status = sa.Column(sa.Boolean(), default=True)
    updated_at = sa.Column(sa.DateTime(timezone=True), default=func.now(), onupdate=func.now())
    created_at = sa.Column(sa.DateTime(timezone=True), default=func.now())
    session = SessionManager().session_factory(dburi=beat_dburi)
